var curpage = 1;
var hasmore = true;
$(function() {
	"use strict";

    var e = getCookie("key");
    var member_type = getUserType();
    if(member_type == ''){
        member_type = 3;
    }

    $('body').on('tap', '.home-category .toggle', function(){
        if($(this).hasClass('active')){
            $(this).removeClass('active')
            $('.category-nav').removeClass('active')
        }else{
            $(this).addClass('active')
            $('.category-nav').addClass('active')
        }
    });

    function loadTimePeriod(time_begin) {
    	var thisObj = $('.time-group-item[data-time_begin="'+time_begin+'"]');
    	var timeGroupObj = $('.time-group');

    	$('.time-group-item').removeClass('time-active');
	    thisObj.addClass('time-active');
	    window.time_begin = time_begin;
	    window.time_end = thisObj.data('time_end');
	    // 首次加载，自动滚动
	    if(!window.defaultTimePeriodT && thisObj.position()) {
		    timeGroupObj.scrollLeft(timeGroupObj.scrollLeft() + thisObj.position().left - 160);
	    }

	    if(window.nextTimePeriod) {
		    if(window.nextTimePeriodT) {
			    // 清除定时
			    clearTimeout(window.nextTimePeriodT);
		    }

		    window.todayTimePeriodT = new Date().getTime();
		    // 下一个时段刷新页面
		    window.nextTimePeriodT = setTimeout(function () {
		    	// 时段重置
		    	window.timePeriodReset = true;
		    	if(new Date(window.defaultTimePeriodT).getDay() !== new Date(window.todayTimePeriodT).getDay()) {
		    		pageLoad(); // 页面重新加载（跨天）
			    } else {
				    timePeriodInit();   // 只跳转时段
			    }
		    }, window.nextTimePeriod * 1000 - new Date().getTime());
	    }

	    // 记录当前时段
	    window.defaultTimePeriodT = time_begin;

        if(window.notFirstLoad) {
            // 页面滚动到顶部
            $('html,body').scrollTop($('.item-goods').offset().top - $('#header').height() - (localCache('STATUS_BAR_HEIGHT') || 0));
        } else {
            window.notFirstLoad = true;
        }

        curpage = 1;
        hasmore = true;
        get_list();
    }

    function  get_list(){
    	// 加载中不再次加载
	    if(window.listLoading || !hasmore) return;

        $(".sctouch-norecord").remove();
        let moreObj = $('.list-more');
        if(moreObj.length == 0) {
            moreObj = $('<div class="list-more"></div>');
            $('.item-goods .goods-list').after(moreObj);
        } else {
	        moreObj.html('');
        }

        if(curpage === 1) {
            $(".goods-list").html('');
            moreObj.html('');
            // 初始化加载
            var html = '    <div class="sctouch-norecord search">\n' +
                '        <div class="norecord-ico"><i class="iconfont"></i></div>\n' +
                '        <dl>\n' +
                '            <dt>数据加载中...</dt>\n' +
                '        </dl>\n' +
                '    </div>';
            $('.goods-list').html(html);
        }else{
            moreObj.html('<li class="loading"><div class="spinner"><i></i></div>数据读取中</li>');
        }
	    window.listLoading = true;
        $.getJSON(ApiUrl + "/goods/goods_list.html?page=" + curpage + "&pagesize=" + pagesize, {
            time_begin: window.time_begin,
            time_end: window.time_end,
            key: getCookie('key')
        }, function (data) {
	        window.listLoading = false;
        	if(data.page == 1) {
		        $(".goods-list").html('');
	        }

            data.result.member_type = member_type;
            moreObj.html('');
            $(".sctouch-norecord").remove();
            curpage++;
            var html = template('goods_list', data);
            $('.item-goods .goods-list').append(html);
            hasmore = data.hasmore;

            if(!hasmore && data.page > 1) {
	            moreObj.html('已经没有更多了');
            }
        });
    }

    // 时间轴点击
    $('body').on('tap', '.time-group-item', function () {
		loadTimePeriod($(this).data('time_begin'));
    });

    //记录页面滚动位置
    $(window).scroll(function (e) {
        window.windowScrollTop = Math.max($('html').scrollTop(), $('body').scrollTop());
        let opcity = Math.min(1, window.windowScrollTop/250);
        // 滚动监控顶部
	    $('.sctouch-home-top').css({
		    background: opcity < 0.1 ? 'transparent' : 'rgba(234, 49, 35, '+opcity+')'
	    });
	    if (window.defaultTimePeriodT && $(window).scrollTop() + $(window).height() > $(document).height() - 1) {
		    get_list();
	    }
    });

    // 初始时段
    function timePeriodInit() {

        var defaultTimeGroupItem;
        // 时段不需要重设
        if(!window.timePeriodReset) {
            defaultTimeGroupItem = $('.time-group-item[data-time_begin="'+window.defaultTimePeriodT+'"]');
            let timeGroup = $('.time-group');
            timeGroup.scrollLeft(window.timePeriodScrollLeft);
        } else {
            //首次加载初始化为当前时段 今天
            defaultTimeGroupItem = $('.today.time-group-item').eq(0);

	        let nowDate = Date.parse(new Date()) / 1000;
            $('.today.time-group-item').each(function () {
                var begin_time = $(this).attr("data-time_begin");
                var end_time = $(this).attr("data-time_end");
                if (nowDate > begin_time && nowDate < end_time) {
                    defaultTimeGroupItem = $(this);
                    window.nextTimePeriod = $(this).next('.time-group-item').data('time_begin');        // 下一个时段记录
                }
            });
        }

	    window.timePeriodReset = false;
        window.defaultTimePeriodT = null;

        // 初始化滚动条位置
        $('html, body').scrollTop(window.windowScrollTop || 0);

        loadTimePeriod(defaultTimeGroupItem.data('time_begin'));
    }
    //消息通知
    function message() {
        baseApi.post("/Shop/message_num",
            function (e) {
        	    var noticeDot = $('#header .msg .notice');
        	    if(noticeDot.length === 0) {
		            noticeDot = $('<em class="notice"></em>');
		            $('#header .msg i').before(noticeDot);
	            }
                if(e.total > 0){
                	noticeDot.show();
                } else {
                	noticeDot.hide();
                }
            })
    }

    function pageLoad() {
        message();
        $.ajax({
            url: ApiUrl + "/index/app",
            type: 'get',
            dataType: 'json',
            success: function(result) {
                var data = result.result;
                //goodsclass
                var html = '';
                $.each(data,function(k, v) {
                    switch (k) {
                        case 'nav_list':
                            $("#main-navlist").html(template(k, data));
                            break;
                        case 'adv_list':
                            $("#main-container1").html(template(k, data));
                            break;
                        case 'extral':
                            break;
                        default:
                            html += template(k, data);
                    }
                });

                $("#main-container2").html(html);

	            $( '.time-group').unbind().scroll(function () {
		            // 记录滚动条滚动的位置
		            var timeGroupObj = $('.time-group');
		            window.timePeriodScrollLeft = timeGroupObj.scrollLeft();
	            });

	            setTimeout(function () {
		            window.timePeriodReset = true;
		            // 初始化商品时段
		            timePeriodInit();
	            }, 100);

                $('.adv_list').each(function() {
                    if ($(this).find('.item').length < 2) {
                        $(this).find('.swipe-nav').hide();
                        return;
                    }

                    Swipe(this, {
                        speed: 400,
                        auto: 3000,
                        continuous: true,
                        disableScroll: false,
                        stopPropagation: false,
                        callback: function(index, elem) {
                            $(elem).parents('.adv_list').find('.swipe-nav em').removeClass('active');
                            $(elem).parents('.adv_list').find('.swipe-nav em').eq(index).addClass('active');
                        },
                        transitionEnd: function(index, elem) {}
                    });
                });
            }
        });
    }

	// 页面数据重新加载
	window.pageReload = function () {
		// window.statusBarResetDisabled = false;  // 允许重设头部
		// window.timePeriodReset = true;
		// window.notFirstLoad = false;
		message();
		// memberCheck();
		getCartCount();
		// timePeriodInit();
	};
	// 页面数据重新加载
	window.pageReShow = function () {
		window.statusBarResetDisabled = false;  // 允许重设头部
		window.timePeriodReset = true;
		window.notFirstLoad = false;
		timePeriodInit();
	};

    mui.init({
        keyEventBind: {
            backbutton: true //开启back按键监听
        }
    });

    // 页面初始化
    pageLoad();

    mui.plusReady(function () {
    	getCurrentWindow().id = 'mall/index';
	    var StatusbarHeight = plus.navigator.getStatusbarHeight() || 20;
	    localCache('STATUS_BAR_HEIGHT', StatusbarHeight, 30);
	    $('.sctouch-home-top').css({
		    'padding-top': StatusbarHeight
	    });
	    plus.navigator.setStatusBarStyle('light');

        var tuichu = "再按一次退出程序";
        var backButtonPress = 0;

        // 关闭所有无用窗口
        // clearAllWindows();
        mui.back = function(event) {
            backButtonPress++;
            if(backButtonPress > 1) {
                var main = plus.android.runtimeMainActivity();
                main.moveTaskToBack(false);
                return false;
            } else {
                plus.nativeUI.toast(tuichu);
            }
            setTimeout(function() {
                backButtonPress = 0;
            }, 1000);
            return false;
        };

	    //仅支持竖屏显示
	    plus.screen.lockOrientation("portrait-primary");

	    // document.addEventListener("newintent", function() {
        //     mui.toast('消息点击触发');
	    //     openWebviewFromOthers();
	    // });
		//
	    // plus.push.addEventListener("click", function(msg) {
        //     mui.toast('点击');
	    //     console.log("push click");
	    //     pushGetRun(msg.payload);
	    // }, false);
	    // plus.push.addEventListener("receive", function(msg) {
	    //     mui.toast('接收消息提醒');
	    //     //获取透传数据
	    //     var data = JSON.parse(msg.payload);
	    //     //创建本地消息
	    //     plus.push.createMessage(data.content, data.payload, {
	    //        title: data.title,
	    //        cover: false
	    //     });
	    // }, false);
        // openWebviewFromOthers();
	});
	function pushGetRun(payload) {
	    payload = JSON.parse(payload);
	    var id = payload.id;
	    var autoShow = payload.autoshow;
	    var event = payload.event;
	    var params = JSON.stringify(payload.params);
	    //用参数打开指定页面   ......
	}
	//获取通知栏（app未启动）点击、第三方程序启动本app
	function openWebviewFromOthers() {
	    var args = plus.runtime.arguments;
	    if(args) {
	        pushGetRun(args);
	    }
	}
	$(document).on();
});

